package com.example.netty;

import javax.annotation.Resource;

import com.example.netty.server.NettyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

/**
 * Netty服务
 * 伴随spring启动而启动
 * 伴随spring停止而停止
 *
 * @author lizhi
 */
@Component
public class NettyApplicationListener implements ApplicationListener<ApplicationEvent> {
    private final static Logger logger = LoggerFactory.getLogger(NettyApplication.class);
    @Resource
    NettyServer server;

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ApplicationReadyEvent) {
            logger.info("ApplicationReadyEvent");
            server.start();
        } else if (applicationEvent instanceof ContextClosedEvent) {
            logger.info("ContextClosedEvent");
            server.stopGracefully();
        }
    }
}
